package com.stm.bi.report;

import com.stm.bi.core.util.DateUtils;
import com.stm.bi.dto.query.DeptChartQuery;
import com.stm.bi.dto.vo.YesterdayVO;
import com.stm.bi.model.Chart;
import com.stm.framework.core.context.UserHolder;
import com.stm.framework.core.util.FileResourceLoader;
import com.stm.framework.dbcp.JdbcService;
import com.stm.framework.dto.Response;
import com.stm.saas.api.ProductConfigRemoteService;
import com.stm.saas.dto.vo.ProductConfigVO;
import com.stm.ucenter.api.DeptRemoteService;
import com.stm.ucenter.api.ShopRemoteService;
import com.stm.ucenter.dto.query.org.DeptListQry;
import com.stm.ucenter.dto.query.org.ShopListQry;
import com.stm.ucenter.dto.vo.org.DeptVO;
import com.stm.ucenter.dto.vo.org.ShopQueryVO;
import com.stm.ucenter.model.Shop;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import java.math.RoundingMode;

import static com.stm.bi.constant.IndexConstants.*;
import static com.stm.bi.constant.PlanConstants.TYPE_MONTH;

/**
 * @author liuyx
 * @date 2025/2/13 16:18
 */
@Component
public class ShopRankingChartQueryExe extends AbsChartQueryExe<DeptChartQuery, Chart<YesterdayVO>> {
    @Resource
    protected JdbcService jdbcService;

    @Resource
    protected ProductConfigRemoteService productConfigRemoteService;

    @Resource
    private ShopRemoteService shopRemoteService;

    @Resource
    private DeptRemoteService deptRemoteService;

    @Override
    public Chart<YesterdayVO> query(Long orgId, String orgNo, DeptChartQuery query) {
        Chart chartVO = new Chart();
        YesterdayVO yesterdayVO = new YesterdayVO();
        chartVO.setExtend(yesterdayVO);
        chartVO.getItems().add(SALES_INDEX_NAME);

        Long deptId = query.getDeptId();
        if (deptId == null) {
            deptId = UserHolder.getLoginUser().getDeptId();
        }

        Response<List<ShopQueryVO>> shopsResp = shopRemoteService.selectList(new ShopListQry().setDeptId(deptId));
        List<String> deptIds = shopsResp.getData().stream()
                .map(Shop::getDeptId)
                .map(Object::toString)
                .collect(Collectors.toList());


        String deptIdsStr = String.join(",", deptIds);
        if(deptIds.isEmpty()) {
            return chartVO;
        }

        String selectSql = FileResourceLoader.getResourceAsString("/sql/adsBaseDefaultSales.sql");
        selectSql = selectSql.replace("IN (?)", "IN (" + deptIdsStr + ")");

        Response<ProductConfigVO> prodResp = productConfigRemoteService.selectByOrgId(UserHolder.getOrgId());
        String salesDefinition = "dealing";
        if(prodResp != null && prodResp.getData() != null) {
            salesDefinition = prodResp.getData().getSalesDefinition();
        }
        if("delivery".equals(salesDefinition)) {
            salesDefinition = "dealing";
        }

        List<Map> maps = jdbcService.selectList(selectSql, new Object[]{orgId,
                TYPE_MONTH,
                salesDefinition,
                DateUtils.getCurrentDate().substring(0, 7),
                DateUtils.getCurrentDate().substring(0, 7)});

        maps.sort(Comparator.comparing((Map m) -> ((BigDecimal) m.get(SALES_AMOUNT_FIELD))).reversed());
        List<Map> res = maps.stream().limit(10).collect(Collectors.toList());


        if (res.isEmpty()) {
            return chartVO;
        }

        List<DeptVO> deptVOList = deptRemoteService.selectList(
                        new DeptListQry().setIds(deptIds.stream().map(Long::parseLong).collect(Collectors.toList())))
                .getData();
        Map<Long, String> deptMap = deptVOList.stream().collect(Collectors.toMap(DeptVO::getId, DeptVO::getName));
        List<List<Object>> datas = new ArrayList<>();
        for (Map re : res) {
            deptId = (Long) re.get("dept_id");
            String deptName = deptMap.get(deptId);
            datas.add(Arrays.asList(deptName,
                    (re.get(SALES_AMOUNT_FIELD) == null ? BigDecimal.ZERO : (BigDecimal) re.get(SALES_AMOUNT_FIELD)).setScale(2, RoundingMode.HALF_UP)));
        }

        chartVO.setDatas(datas);
        return chartVO;
    }

    @Override
    public String getReportName() {
        return "店铺排名";
    }
}